package com.example.springboot_code_read.genericConverter;

import com.example.springboot_code_read.annotation.DateFormat;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Set;

public class AnnotatedStringToDateConverter implements GenericConverter {

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Date.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {

        if (null == source)
            return null;

        String dateStr = (String) source;
        DateFormat annotation = targetType.getAnnotation(DateFormat.class);

        // 如果目标字段上没有 DateFormat 注解，则抛出异常
        if (annotation == null) {
            throw new IllegalArgumentException("目标字段上缺少DateFormat注解");
        }

        try {
            SimpleDateFormat format = new SimpleDateFormat(annotation.value());
            return format.parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException("无法解析日期", e);
        }

    }


}
